import os
from dotenv import load_dotenv
from playwright.sync_api import sync_playwright

from src.utils.BrowserUtil import BrowserUtil
from src.utils.DragVerifyImageUtil import DragVerifyImageUtil

# 加载环境变量
load_dotenv()

class OceanEngine:

    def __init__(self, browser: BrowserUtil):
        # 初始化浏览器工具
        self.browser_util: BrowserUtil = browser
        self.playwright = None
        self.browser = None
        self.page = None

    def login(self):
        # 启动Playwright
        self.playwright = sync_playwright().start()
        # 启动浏览器
        self.browser = self.playwright.chromium.launch(headless=False)
        # 打开新页面
        self.page = self.browser.new_page()
        # 尝试直接访问目标页面
        self.page.goto("https://business.oceanengine.com/site/account-manage/ad/bidding/superior/account")
        self.page.wait_for_timeout(2000)

        # 检查当前页面的 URL
        if "login" in self.page.url:
            print("需要登录...")
            # 从环境变量中获取登录页面地址
            login_url = os.getenv("OCEAN_ENGINE_LOGIN_URL")
            # 访问登录页面
            self.page.goto(login_url)
            print(f"打开登录页面...")
            self.page.wait_for_timeout(1500)
            # 点击登录按钮
            self.page.locator("#root-common-header > div > div.nav-right > div.nav-button").click()
            print(f"点击登录按钮...")
            self.page.wait_for_timeout(1500)
            # 从环境变量中获取账号和密码
            email = os.getenv("OCEAN_ENGINE_EMAIL")
            password = os.getenv("OCEAN_ENGINE_PASSWORD")
            # 输入账号和密码
            self.page.locator("input[name='email']").fill(email)
            print(f"输入账号...")
            self.page.wait_for_timeout(1500)
            self.page.locator("input[name='password']").fill(password)
            print(f"输入密码...")
            self.page.wait_for_timeout(1500)
            # 同意条款
            self.page.locator("#account-sdk > section > div.account-center-input-agreement > div > div > div").click()
            print(f"同意条款...")
            self.page.wait_for_timeout(1500)
            # 点击登录
            self.page.locator("#account-sdk > section > div.account-center-submit > button").click()
            print(f"点击登录按钮...")
            self.page.wait_for_timeout(3000)

            # 获取iframe元素
            iframe = self.page.query_selector("iframe")
            # 检查iframe是否存在
            if iframe is not None:
                # 切换到iframe
                iframe_content = iframe.content_frame()

                # 获取滑块验证码图片的URL
                captcha = iframe_content.query_selector("#captcha-verify_img_slide")
                slider_img_url = captcha.get_attribute('src')
                print(slider_img_url)

                # 获取背景验证码图片的URL
                verify = iframe_content.query_selector("#captcha_verify_image")
                background_img_url = verify.get_attribute('src')
                print(background_img_url)

                # 获取验证码图片元素的尺寸
                background_element_size = verify.bounding_box()
                background_element_width = background_element_size['width']
                background_element_height = background_element_size['height']

                slider_element_size = captcha.bounding_box()
                slider_element_width = slider_element_size['width']
                slider_element_height = slider_element_size['height']

                # 下载并处理验证码图片
                drag_verify_image_util = DragVerifyImageUtil()
                drag_verify_image_util.get_images(
                    background_img_url,
                    slider_img_url,
                    background_size=(int(background_element_width), int(background_element_height)),
                    slider_size=(int(slider_element_width), int(slider_element_height))
                )
                verify_background_img, verify_slider_img = drag_verify_image_util.preprocess_image()
                drag_x = drag_verify_image_util.find_slider_position(verify_background_img, verify_slider_img)
                print(f"待移动像素：" + str(drag_x))

                # 获取滑块元素
                slider_div = iframe_content.query_selector("#vc_captcha_box > div > div > div.captcha-slider.captcha_verify_slide--button > div > div.dragger-box > div.dragger-item")

                # 获取滑块的初始位置
                slider_box = slider_div.bounding_box()
                print(f"开始滑动滑块验证码...")
                # 使用鼠标拖动滑块
                self.page.mouse.move(slider_box['x'] + slider_box['width'] / 2, slider_box['y'] + slider_box['height'] / 2)
                self.page.mouse.down()
                self.page.mouse.move(slider_box['x'] + slider_box['width'] / 2 + drag_x, slider_box['y'] + slider_box['height'] / 2, steps=50)
                self.page.mouse.up()

            # 切换到账户tab页
            self.page.wait_for_timeout(2000)
            self.page.locator("#bp-app > div.style_header-container__VQjDT.false > div.style_header-links__2gcut > div.style_header-links-item__K-eRR.style_active__U09oz").click()
            print(f"切换到账户tab页...")
            # 切换到账户列表页
            self.page.wait_for_timeout(2000)
            self.page.locator("#app > div > div.account-content > div > div.oc-card > div > div > div.detail-content > div.oc-tabs.oc-tabs__line.oc-tabs__md.oc-tabs__align.oc-tabs__align-end.table-tabs > div > div.ovui-tabs__nav > div.ovui-tabs__nav-list-scroll-container.ovui-tabs__nav-list-scroll-container--disabled-left.ovui-tabs__nav-list-scroll-container--disabled-right > div > div:nth-child(2) > div > div > div").click()
            print(f"切换到账户列表页...")
            self.page.wait_for_timeout(2000)
        else:
            print("已登录，跳过登录逻辑...")
            # 切换到账户tab页
            self.page.wait_for_timeout(2000)
            self.page.locator("#bp-app > div.style_header-container__VQjDT.false > div.style_header-links__2gcut > div.style_header-links-item__K-eRR.style_active__U09oz").click()
            print(f"切换到账户tab页...")
            # 切换到账户列表页
            self.page.wait_for_timeout(2000)
            self.page.locator("#app > div > div.account-content > div > div.oc-card > div > div > div.detail-content > div.oc-tabs.oc-tabs__line.oc-tabs__md.oc-tabs__align.oc-tabs__align-end.table-tabs > div > div.ovui-tabs__nav > div.ovui-tabs__nav-list-scroll-container.ovui-tabs__nav-list-scroll-container--disabled-left.ovui-tabs__nav-list-scroll-container--disabled-right > div > div:nth-child(2) > div > div > div").click()
            print(f"切换到账户列表页...")
            self.page.wait_for_timeout(2000)

        self.page.wait_for_timeout(3000)

    def close(self):
        # 关闭浏览器
        if self.browser:
            self.browser.close()
        # 停止Playwright
        if self.playwright:
            self.playwright.stop()


if __name__ == "__main__":
    # 创建OceanEngine实例并执行登录
    ocean_engine = OceanEngine(BrowserUtil())
    ocean_engine.login()
